package com.mingqijia.gassafety.webserver.service.workorder.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.entity.vo.DeviceOrderCustTypeVO;
import com.mingqijia.gassafety.db.entity.vo.WorkOrderAndSmartKitVO;
import com.mingqijia.gassafety.db.mapper.WorkOrderHistoryMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.CustTypeEnum;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;

import java.util.Date;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 工单记录表 服务实现类
 * </p>
 *
 * @author guoliang.lao
 * @since 2022-09-15
 */
@Service
@Slf4j
public class WorkOrderHistoryServiceImpl extends ServiceImpl<WorkOrderHistoryMapper, WorkOrderHistory> implements WorkOrderHistoryService {

    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;
    @Override
    public void updateHandleStatus(String orderNo,Integer handleStatus,Date completedTime) {
        LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkOrderHistory::getOrderNo,orderNo).eq(WorkOrderHistory::getIsDeleted,0);
        WorkOrderHistory workOrderHistory = new WorkOrderHistory();
        workOrderHistory.setHandleStatus(handleStatus);
        if (handleStatus.equals(1)) {
            //完成记录完工时间
            if (completedTime != null) {
                workOrderHistory.setCompleteTime(completedTime);
            } else {
                workOrderHistory.setCompleteTime(new Date());
            }
        }
        this.update(workOrderHistory,lambdaQueryWrapper);
    }

    @Override
    public void updateDeviceId(String orderNo, String deviceId, String spId) {
        LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkOrderHistory::getOrderNo,orderNo)
                .eq(WorkOrderHistory::getDeviceId, deviceId)
                .eq(WorkOrderHistory::getSpId, spId).eq(WorkOrderHistory::getIsDeleted,0);
        WorkOrderHistory workOrderHistory = new WorkOrderHistory();
        if (workOrderHistory != null) {
            //删除工单设备设备
            workOrderHistory.setDeviceId("");
            this.updateById(workOrderHistory);
        }
    }

    @Override
    public void insertHistory(WorkOrderHistory workOrderHistory) {
        LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkOrderHistory::getOrderNo,workOrderHistory.getOrderNo())
                .eq(WorkOrderHistory::getDeviceId,workOrderHistory.getDeviceId())
                .eq(WorkOrderHistory::getSpId,workOrderHistory.getSpId());
        WorkOrderHistory history = this.getOne(lambdaQueryWrapper);
        if (history == null) {
            String woSeq = WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
            workOrderHistory.setWoSeq(woSeq);
            this.save(workOrderHistory);
        } else {
            if (history.getIsDeleted()) {
                WorkOrderHistory update = new WorkOrderHistory();
                update.setId(history.getId());
                update.setIsDeleted(false);
                this.updateById(update);
            }
        }
    }

    @Override
    public void deleteHistory(String orderNo,String deviceId,String spId) {
        LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkOrderHistory::getOrderNo,orderNo)
                .eq(WorkOrderHistory::getDeviceId,deviceId)
                .eq(WorkOrderHistory::getSpId,spId);
        WorkOrderHistory history = new WorkOrderHistory();
        history.setIsDeleted(true);
        this.update(history,lambdaQueryWrapper);
    }

    @Override
    public void deleteHistoryByReturn(String deviceId, String subsCode,String spId, Integer workSystem) {
        LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkOrderHistory::getWorkSystem,workSystem)
                .eq(WorkOrderHistory::getDeviceId,deviceId)
                .eq(WorkOrderHistory::getSubsCode,subsCode)
                .eq(WorkOrderHistory::getSpId,spId)
                .eq(WorkOrderHistory::getHandleStatus,0);
        WorkOrderHistory history = new WorkOrderHistory();
        history.setIsDeleted(true);
        this.update(history,lambdaQueryWrapper);
    }

    @Override
    public WorkOrderHistory selectPkidByImei(String imei,String spId,Integer orderType,Integer orderChannel) {
        return workOrderHistoryMapper.selectPkidByImei(imei,spId,orderType,orderChannel);
    }

    @Override
    public List<WorkOrderHistory> queryPkidByImeis(List<String> imeiList, String spId, Integer orderType, Integer orderChannel) {
        return workOrderHistoryMapper.queryPkidByImeis(imeiList, spId, orderType, orderChannel);
    }

    @Override
    public int queryCountByImeis(String imei, String spId) {
        return workOrderHistoryMapper.selectCountByImei(imei,spId);
    }

    @Override
    public int queryCountByImeis(List<String> imei, String spId) {
        return workOrderHistoryMapper.queryCountByImei(imei, spId);
    }

    @Override
    public List<WorkOrderAndSmartKitVO> selectWorkOrderAndSmartKitByRecordId(List<String> recordIds) {
        return workOrderHistoryMapper.selectWorkOrderAndSmartKitByRecordId(recordIds);
    }

    /**
     * 进行中的工单
     * @param subsCode
     * @param spId
     * @return
     */
    @Override
    public void existWorkOrder(String subsCode, String spId){
        if (StringUtils.isEmpty(subsCode))return;
        List<WorkOrderHistory>  workOrderHistories=workOrderHistoryMapper.selectBySubsCode(subsCode,spId);
        if (!CollectionUtils.isEmpty(workOrderHistories)) throw new BizException("设备工单进行中");
    }

    @Override
    public WorkOrderHistory selectByOrderNo(String orderNo) {
        return workOrderHistoryMapper.selectByOrderNo(orderNo);
    }

    @Override
    public List<WorkOrderHistory> queryByOrderNo(List<String> orderNos) {
        //批量查询工单信息
        QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(WorkOrderHistory::getOrderNo, orderNos)
                .eq(WorkOrderHistory::getIsDeleted, 0);
        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Integer> selectDeviceLastUseCustType(String spId, List<String> deviceIds) {
        Map<String,Integer> deviceCustTypeMap = new HashMap<>();
        List<DeviceOrderCustTypeVO> deviceOrderCustTypeVOS = workOrderHistoryMapper.selectDeviceLastUseCustType(spId,deviceIds);
        if (!CollectionUtils.isEmpty(deviceOrderCustTypeVOS)) {
            deviceCustTypeMap = deviceOrderCustTypeVOS.stream().collect(Collectors.toMap(DeviceOrderCustTypeVO::getDeviceId, DeviceOrderCustTypeVO::getCustType));
        }
        return deviceCustTypeMap;
    }

    @Override
    public int getOrderLaunchCustType(Consumer consumer){
        int orderCustType = Constants.ORDER_CUST_TYPE_DEFAULT;
        try {
            String spId = consumer.getSpId();
            log.info("getOrderLaunchCustType consumer:{}", JSONObject.toJSONString(consumer));
            if (!StringUtils.isEmpty(consumer.getSubsCode())) {
                if (CustTypeEnum.CUST_TYPE_1.getCustTypeCode().equals(consumer.getCustTypeCode())) {
                    orderCustType = Constants.ORDER_CUST_TYPE_PERSONAL;
                } else {
                    orderCustType = Constants.ORDER_CUST_TYPE_COMPANY;
                }
                log.info("getOrderLaunchCustType consumer orderCustType:{}", orderCustType);
            } else if (consumer.getId()>0){
                DeviceOrderCustTypeVO deviceOrderCustTypeVO = workOrderHistoryMapper.selectLastUseCustTypeByConsumerId(spId, consumer.getId());
                if (null != deviceOrderCustTypeVO && null != deviceOrderCustTypeVO.getCustType() && deviceOrderCustTypeVO.getCustType() > 0) {
                    orderCustType = deviceOrderCustTypeVO.getCustType();
                }
                log.info("getOrderLaunchCustType order orderCustType:{}", orderCustType);
            }
        }catch (Exception e){
            log.error("getOrderLaunchCustType:",e);
        }
        return orderCustType;
    }
}
